package com.lp.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class WriteLogUtil
{
	public final static String DBException_Type = "DataBase Exception";
	public final static String OtherException_Type = "Other Exception";
	private final static String Mark_Flag = "---------------------------------";
	
	private static String DBException_Path;
	private static  String OtherException_Path;
	static
	{
		Properties properties = new Properties();
		InputStream inputStream = WriteLogUtil.class.getClassLoader().getResourceAsStream("etc/path.properties");
		
		try
		{
			properties.load(inputStream);
			
			DBException_Path = properties.getProperty("DBExceptionLog");
			OtherException_Path = properties.getProperty("OtherExceptionLog");
			
		}
		catch (IOException e)
		{
			throw new RuntimeException(e.getMessage(),e);
		}
		
		finally
		{
			try
			{
				if(inputStream != null)
					inputStream.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException(e.getMessage(),e);
			}
			finally
			{
				inputStream = null;
				properties = null;
				System.gc();
			}
		}
		
	}
	
	public static void writeLog(String Exception_Type,String logContent)
	{
		File file = null;
		if(DBException_Type.equals(Exception_Type))
		{
			file = new File(DBException_Path);
			
		}
		
		else if(OtherException_Type.equals(Exception_Type))
		{
			file = new File(OtherException_Path);
		}
		
		
		
		if(!file.exists())
		{
			try
			{
				file.createNewFile();
			}
			catch (IOException e)
			{
				throw new RuntimeException(e.getMessage());
			}
		}
		
		
		FileWriter fileWriter = null;
		try
		{
			fileWriter = new FileWriter(file,true);
			
			
			fileWriter.write(getLogHeader() + logContent + "\r\n" + Mark_Flag + "\r\n\r\n");
		}
		catch (IOException e)
		{
			throw new RuntimeException(e.getMessage());
		}
		finally
		{
			try
			{
				if(fileWriter != null)
					fileWriter.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException(e.getMessage());
			}
			finally
			{
				fileWriter = null;
				file = null;
				System.gc();
			}
		}
	}
	
	
	
	private static String getLogHeader()
	{
		return "date:" + StringUtil.getFormateDate(new Date()) + "\r\n" + "error:";
	}

}
